package com.gaoyang.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gaoyang.domain.DianPingUser;
import com.gaoyang.domain.GongHuiUser;
import com.gaoyang.util.*;
import com.gaoyang.util.net.HttpResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Component
public class GonghuiTask {

    private static Logger logger = LogManager.getLogger(GonghuiTask.class);

    public String getLoginToken(DianPingUser user) {
        String token = "";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("login_name", user.getUa());
        paramMap.put("password", user.getPassword());
        paramMap.put("jpush_id", "");
        String url_login = API_URL.GONGHUI.URL_LOGIN;
        String queryString = HttpUtils4Black.sendGet(url_login, paramMap, "");
        logger.info(user.getUserName() + "获取token:" + queryString);
        JSONObject loginObj = JSONObject.parseObject(queryString);
        if (loginObj.getString("errcode").equals("0")) {
            token = loginObj.getString("token");
        }
        return token;
//        if (isSingle) {
//            reportGonghuiInfo(actId, user, token_gaoyang, count, firm_id);
//        } else {
//            reportGonghuiListInfo(actId, count, user, token_gaoyang, firm_id);
//        }
    }

    /**
     * 调用工会活动列表
     * @param project_id
     * @param user
     */
    public void reportGonghuiListInfo(String project_id, String qiang_count, GongHuiUser user, String firm_id){
        String url = API_URL.GONGHUI.URL_LIST;
        Map<String, String> paramMap1 = new HashMap<>();
        paramMap1.put("project_id", project_id);
        paramMap1.put("service_name", "");
        paramMap1.put("page", "1");
        paramMap1.put("size", "10");
        paramMap1.put("search_type", "1");
        paramMap1.put("token", user.getToken());
        String tokenString = HttpUtils4Black.sendGet(url, paramMap1, "");
        JSONArray array = JSONArray.parseArray(tokenString);
        //3.遍历要抢的产品列表
        for (Object obj : array) {
            JSONObject jsonObject = (JSONObject) obj;
            String name = jsonObject.getString("name");
            if (name.contains("图书")) {
                qiang_count = "1";
            }
//            else if (name.contains("观光塔")) {
//                qiang_count = "2";
//            } else if (name.contains("亲子")) {
//                qiang_count = "1";
//            } else if (name.contains("电影券")) {
//                qiang_count = "3";
//            } else if (name.contains("蛋糕")) {
//                qiang_count = "1";
//            } else if (name.contains("图书")) {
//                qiang_count = "1";
//            } else if (name.contains("理发")) {
//                qiang_count = "3";
//            } else if (name.contains("陶瓷")) {
//                qiang_count = "1";
//            }
            else {
                continue;
            }
            int count = jsonObject.getInteger("count");
            String start_at = jsonObject.getString("start_at");
            start_at = start_at.substring(0, start_at.length()-2);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime server = LocalDateTime.parse(start_at, dtf);
            LocalDateTime fire = server.minusMinutes(10);
            LocalDateTime now = LocalDateTime.now();
            //4.判断库存和执行时间
            if (count > 0
//                        && now.isAfter(fire)
                    ) {
                //5.调用验证是否可抢接口
                String verify_url = API_URL.GONGHUI.URL_VERIFY;
                int id = jsonObject.getInteger("id");
                Map<String, String> paramMap3 = new HashMap<>();
                paramMap3.put("service_id", id + "");
                paramMap3.put("token", user.getToken());
                String verifyString = HttpUtils4Black.sendGet(verify_url, paramMap3, "");
                logger.info(user.getUserName() + ":verifyString:" + name + "调用验证是否可抢接口:" + verifyString);
                JSONObject verifyObj = JSONObject.parseObject(verifyString);
                if (verifyObj.getString("errcode").equals("0")) {
                    //6.调用抢票接口
                    qiangPiao(id, name, qiang_count, user.getToken(), user.getReceive_id(), firm_id, user.getUserName());
                }
            } else {
                logger.info(user.getUserName() + " " + name+ " 抢票尚未触发 数量：" + count + " 触发时间：" + now.isAfter(fire));
            }
        }

        //生抢列表里的id程序 生抢
//        int[] stringArray = {33926, 33915, 33914, 33913, 33912};
//        for (int id : stringArray) {
//                String verify_url = API_URL.GONGHUI.URL_VERIFY;
//                Map<String, String> paramMap3 = new HashMap<>();
//                paramMap3.put("service_id", id + "");
//                paramMap3.put("token", user.getToken());
//                String verifyString = HttpUtils4Black.sendGet(verify_url, paramMap3, "");
//                logger.info(user.getUserName() + " verifyString:" + id + "调用验证是否可抢接口:" + verifyString);
//                JSONObject verifyObj = JSONObject.parseObject(verifyString);
//                if (verifyObj.getString("errcode").equals("0")) {
//                    //6.调用抢票接口
//                    qiangPiao(id, id + "", qiang_count, user.getToken(), user.getReceive_id(), firm_id, user.getUserName());
//                }
//        }
    }

    public void reportGonghuiInfo(String project_id, String qiang_count, GongHuiUser user, String firm_id){
        String url = API_URL.GONGHUI.URL_LIST_SINGLE;
        Map<String, String> paramMap1 = new HashMap<>();
        paramMap1.put("service_id", project_id);
        String tokenString = HttpUtils4Black.sendGet(url, paramMap1, "");
        JSONObject jsonObject = JSONObject.parseObject(tokenString);
        String name = jsonObject.getString("name");
        int count = jsonObject.getInteger("count");
        String start_at = jsonObject.getString("start_at");
        start_at = start_at.substring(0, start_at.length()-2);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime server = LocalDateTime.parse(start_at, dtf);
        LocalDateTime fire = server.minusMinutes(10);
        LocalDateTime now = LocalDateTime.now();
        if (count > 0) {
            String verify_url = API_URL.GONGHUI.URL_VERIFY;
            int id = jsonObject.getInteger("id");
            Map<String, String> paramMap3 = new HashMap<>();
            paramMap3.put("service_id", id + "");
            paramMap3.put("token", user.getToken());
            String verifyString = HttpUtils4Black.sendGet(verify_url, paramMap3, "");
            logger.info("verifyString:" + user.getUserName() + " " + name + " 调用验证是否可抢接口:" + verifyString);
            JSONObject verifyObj = JSONObject.parseObject(verifyString);
            if (verifyObj.getString("errcode").equals("0")) {
                //6.调用抢票接口
                qiangPiao(id, name, qiang_count, user.getToken(), user.getReceive_id(), firm_id, user.getUserName());
            }
        } else {
            logger.info(user.getUserName() + " " + name+ " 抢票尚未触发 数量：" + count + " 触发时间：" + now.isAfter(fire));
        }
    }


    /**
     * 开始抢票
     * @param id
     * @param name
     * @param count
     * @param token
     * @param receive_id
     */
    private static void qiangPiao(int id, String name, String count, String token, String receive_id, String firm_id, String userName) {
        LocalDateTime now = LocalDateTime.now();
        String reserve_url = API_URL.GONGHUI.URL_RESERVE;
        Map<String, String> paramMap4 = new HashMap<>();
        paramMap4.put("service_id", id + "");
        paramMap4.put("token", token);
        paramMap4.put("receive_id", receive_id);
        paramMap4.put("use_date", DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now));
        paramMap4.put("firm_id", firm_id);
        paramMap4.put("reserve_count", count);
        paramMap4.put("phone", "18601162346");
        String reserveString = HttpUtils4Black.sendGet(reserve_url, paramMap4, "");
        logger.info("reserveString " + reserveString);
        JSONObject reserveObj = JSONObject.parseObject(reserveString);
        if (reserveObj.getString("errcode").equals("0")) {
            //发邮件
            try {
                MailUtil.sendMail(name + " " + userName +" 有票了", userName + " " +  name + ":" + count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}